import 'dart:async';

import 'package:flutter/material.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../news_page.dart';

/// 新闻公告
class HomeNews extends StatefulWidget {
  final List<Link> news;

  const HomeNews({
    Key key,
    @required this.news,
  }) : super(key: key);

  @override
  _HomeNewsState createState() => _HomeNewsState();
}

class _HomeNewsState extends State<HomeNews> {
  PageController _pageController;
  Timer _timer;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _timer = Timer.periodic(Duration(seconds: 3), _callback);
  }

  @override
  void dispose() {
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _onTap,
      child: Container(
        padding: EdgeInsets.all(8.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        width: (375.0 - 8 * 2).w,
        child: Row(
          children: [
            Image.asset(
              "assets/icons/news.png",
              width: 16.w,
              height: 16.w,
            ),
            SizedBox(width: 8.w),
            SizedBox(
              width: 300.w,
              height: 20.w,
              child: PageView.builder(
                scrollDirection: Axis.vertical,
                controller: _pageController,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) => _buildItem(index),
              ),
            ),
            Image.asset("assets/image/arrow_right.png"),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(int index) {
    final link = widget.news[index % widget.news.length];
    return Container(
      alignment: Alignment.centerLeft,
      child: Text(
        "${link.title}",
        style: TextStyle(
          fontSize: 13.sp,
        ),
        maxLines: 1,
      ),
    );
  }

  void _callback(Timer timer) {
    _pageController.nextPage(
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInToLinear,
    );
  }

  void _onTap() {
    Navigator.of(context).pushNamed(NewsPage.routeName);
  }
}
